package cn.hfjava.kz.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hfjava.kz.common.converter.ByteToBase64Converter;
import cn.hfjava.kz.entity.po.Application;
import cn.hfjava.kz.entity.po.Student;
import cn.hfjava.kz.mapper.StudentMapper;
import cn.hfjava.kz.service.impl.ApplicationServiceImpl;
import cn.hfjava.kz.service.impl.StudentServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

@RestController
@RequestMapping("/api/v1/ocr")
@Slf4j
@Tag(name = "文字识别")
public class OcrController {


    @Resource
    private Credential credential;
    @Autowired
    private StudentServiceImpl studentServiceImpl;
    @Autowired
    private ApplicationServiceImpl applicationServiceImpl;
    @Autowired
    private StudentMapper studentMapper;


    @Operation(summary = "身份证识别")
    @PostMapping(value = "/idCardNo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public SaResult queryIDCardOCR(@RequestPart("file") MultipartFile file) throws TencentCloudSDKException, IOException {

        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");

        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化要请求产品的client对象,clientProfile是可选的
        OcrClient client = new OcrClient(credential, "ap-guangzhou", clientProfile);

        //将上传的文件转换成base64编码
        String encodeBytesToBase64 = ByteToBase64Converter.encodeBytesToBase64(file.getBytes());


        // 实例化一个请求对象,每个接口都会对应一个request对象
        IDCardOCRRequest req = new IDCardOCRRequest();
        req.setImageBase64(encodeBytesToBase64);
        req.setCardSide("FRONT");
        //req.setConfig("{\"CropIdCard\":true,\"CropPortrait\":true}");
        // req.setImageUrl("https://ltmyblog.oss-cn-shenzhen.aliyuncs.com/myBlog/article/image-20230924213423855.png");

        // 返回的resp是一个GeneralBasicOCRResponse的实例，与请求对象对应
        IDCardOCRResponse resp = client.IDCardOCR(req);
        // 输出json格式的字符串回包
        String jsonResult = AbstractModel.toJsonString(resp);
        log.info("身份证识别响应结果：{}", jsonResult);
        saveIDCardMessage(resp);
        return SaResult.ok("身份证识别成功").setData(resp);
    }

    public void saveIDCardMessage(IDCardOCRResponse resp) {
        String createdUser = String.valueOf(StpUtil.getExtra("username"));
        Integer userId = StpUtil.getLoginIdAsInt();
        Student student = new Student();
        Application application = new Application();

        if (!(studentMapper.selectCount(new QueryWrapper<Student>().eq("identityId", resp.getIdNum())) > 0)) {
            student.setName(resp.getName());
            student.setPassword(resp.getIdNum().substring(resp.getIdNum().length() - 6));
            student.setIdentityId(resp.getIdNum());
            student.setNation(resp.getNation());
            student.setAddress(resp.getAddress());
            student.setCreatedBy(createdUser);
            student.setUserId(userId);
            studentServiceImpl.save(student);
            application.setStudentId(student.getId());
            application.setGender(resp.getSex());
            DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .appendPattern("yyyy")
                    .appendLiteral('/')
                    .appendPattern("MM")
                    .appendLiteral('/')
                    .appendPattern("dd")
                    .toFormatter();

            application.setBirthdate(LocalDate.parse(resp.getBirth(), formatter));
            application.setDomicile(resp.getAddress());
            applicationServiceImpl.save(application);
        }
    }
}
